package com.controller;

import com.alibaba.fastjson.JSON;
import com.common.shiro.ShiroUtils;
import com.pojo.Admin;
import com.pojo.Result;
import com.server.AdminService;
import com.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @description：登录退出
 */
@Controller
public class LoginController {
    @Resource
    AdminService adminService;
    @Autowired
    RedisUtil redisUtil;

    //登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Result loginPost(String username, String password,String txtCode,HttpSession session){
        System.out.println("username="+username+"--->password="+password);
        Result result = new Result();
        // 比对验证码是否正确
        if ( !(txtCode.equals( session.getAttribute("code") ) ) ) {
            result.setMsg("验证码错误");
        }

        Subject adminifo= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username, password);

        try {
            adminifo.login(token);
            System.out.println(adminifo);
        } catch (UnknownAccountException e) {
            result.setMsg("账号不存在");
            return result;
        } catch (DisabledAccountException e) {
            result.setMsg("账号未启用");
            return result;
        } catch (IncorrectCredentialsException e) {
            result.setMsg("密码错误");
            return result;
        } catch (RuntimeException e) {
            result.setMsg("未知错误,请刷新界面重新登录！"+e.getMessage());
//            result.setMsg(e.getMessage());
            return result;
        }
        Admin admin=adminService.findAdminByLoginName(username);
        String userStr= JSON.toJSONString(admin);
        session.setAttribute("userStr", userStr);
        result.setSuccess(true);
        return result;
    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
    //@ResponseBody
    public String logout() {
        ShiroUtils.logout();
        return "redirect:/" ;
    }

}
